<template>
  <div>
    <p>
      <button @click="list(1)" class="btn btn-white btn-default btn-round">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
      &nbsp;&nbsp;
      <button @click="addModel()" class="btn btn-white btn-default btn-round">
        <i class="ace-icon fa fa-refresh"></i>
        新增
      </button>
    </p>
    <Pagination ref="Pagination" v-bind:list="list"></Pagination>
    <!-- PAGE CONTENT BEGINS -->
    <div class="col-md-3" v-for="course in courses" :key="course.id">
      <div class="thumbnail search-thumbnail">
        <img class="media-object" :src="course.image" />
        <div class="caption">
          <div class="clearfix">
            <span
              style="margin-left: 2px"
              class="pull-right label label-primary info-label"
              >{{ LEVEL | optionKV(course.level) }}</span
            >
            <span
              style="margin-left: 2px"
              class="pull-right label label-primary info-label"
              >{{ CHARGE | optionKV(course.charge) }}</span
            >
            <span class="pull-right label label-primary info-label">{{
              STATUS | optionKV(course.status)
            }}</span>
          </div>

          <h3 class="search-title">
            <a href="#" class="blue">{{ course.name }}</a>
          </h3>

            <div v-for="teacher in teachers.filter(t=>{return t.id===course.teacherId})" :key="teacher.id" class="profile-activity clearfix">
              <div>
                <img v-show="!teacher.image" class="pull-left" src="/ace/assets/images/avatars/avatar5.png">
                <img v-show="teacher.image" class="pull-left" v-bind:src="teacher.image">
                <a class="user" href="#"> {{teacher.name}} </a>
                <br>
                {{teacher.position}}
              </div>
            </div>
            
          <p>
            <span class="blue bolder bigger-150" v-show="course.charge == CHARGE.CHARGE.key"
              ><i  class="fa fa-rmb"></i>&nbsp;{{ course.price }}</span
            >
            <span class="blue bolder bigger-150" v-show="course.charge == CHARGE.FREE.key"
              ><i  class="fa fa-rmb"></i>&nbsp;0</span
            >
          </p>
          <p>{{ course.summary }}</p>
          <p>
            <span class="badge badge-info">{{ course.id }}</span>
            &nbsp;<span class="badge badge-info">排序:{{ course.sort }}</span>
            &nbsp;<span class="badge badge-info"
              >时长:{{ course.time | formatSecond }}</span
            >
            &nbsp;<span class="badge badge-info"
              >报名数:{{ course.enroll }}</span
            >
          </p>
          <div class="btn-group">
            <button
              v-on:click="toChapter(course)"
              class="btn btn-white btn-xs btn-info btn-round"
            >
              大章
            </button>
            <button
              v-on:click="editModel(course)"
              class="btn btn-white btn-xs btn-info btn-round"
            >
              编辑
            </button>
            <button
              v-on:click="contentModel(course)"
              class="btn btn-white btn-xs btn-info btn-round"
            >
              内容
            </button>
            <button
              v-on:click="del(course.id)"
              class="btn btn-white btn-xs btn-warning btn-round"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- Modal -->
    <div
      class="modal fade"
      id="course-form"
      tabindex="10"
      role="dialog"
      aria-labelledby="myModalLabel"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">新增</h4>
          </div>
          <div class="modal-body">
            <form>
              <div class="form-group">
                <label for="name">分类</label>
                <ul id="tree" class="ztree"></ul>
              </div>
              <div class="form-group">
                <label for="name">名称</label>
                <input
                  v-model="course.name"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  id="name"
                  placeholder="名称"
                />
              </div>
              <div class="form-group">
                <label>讲师</label>
                <select v-model="course.teacherId" class="form-control " id="form-field-select-3">
                    <option v-for="o in teachers" :key="o.id" :value="o.id">{{o.name}}</option>
                </select>
              </div>
              <div class="form-group">
                <label for="summary">概述</label>
                <input
                  v-model="course.summary"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  id="summary"
                  placeholder="概述"
                />
              </div>
              <div class="form-group">
                <label for="time">时长</label>
                <input
                  v-model="course.time"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  id="time"
                  placeholder="时长"
                />
              </div>
              <div class="form-group">
                <label for="price">价格(元)</label>
                <input
                  v-model="course.price"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  id="price"
                  placeholder="价格(元)"
                />
              </div>
              <div class="form-group">
                <label for="image">封面</label>
                <File 
                  v-bind:input-id="'image-upload'" 
                  v-bind:text="'上传封面'"
                  v-bind:suffixs="['png','jpg','jpeg']"
                  v-bind:afterUpload="afterUpload"
                  v-bind:use="FILE_USE.COURSE.key"
                  >
                </File>
                <div v-show="course.image" class="row">
                    <div class="col-md-4">
                        <img :src="course.image" class="img-responsive" alt="">
                    </div>
                </div>
              </div>
              <div class="form-group">
                <label for="level">级别</label>
                <select
                  v-model="course.level"
                  class="chosen-select form-control"
                >
                  <option v-for="o in LEVEL" :key="o.key" v-bind:value="o.key">
                    {{ o.value }}
                  </option>
                </select>
                <!-- <input v-model="course.charge" autocomplete="off" type="text" class="form-control" id="charge" placeholder="收费"> -->
              </div>
              <div class="form-group">
                <label for="charge">收费</label>
                <select
                  v-model="course.charge"
                  class="chosen-select form-control"
                >
                  <option v-for="o in CHARGE" :key="o.key" v-bind:value="o.key">
                    {{ o.value }}
                  </option>
                </select>
                <!-- <input v-model="course.charge" autocomplete="off" type="text" class="form-control" id="charge" placeholder="收费"> -->
              </div>
              <div class="form-group">
                <label for="status">状态</label>
                <select
                  v-model="course.status"
                  class="chosen-select form-control"
                >
                  <option v-for="o in STATUS" :key="o.key" v-bind:value="o.key">
                    {{ o.value }}
                  </option>
                </select>
                <!-- <input v-model="course.charge" autocomplete="off" type="text" class="form-control" id="charge" placeholder="收费"> -->
              </div>
              <!-- <div class="form-group">
                <label for="enroll">报名数</label>
                <input
                  v-model="course.enroll"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  id="enroll"
                  placeholder="报名数"
                />
              </div> -->
              <div class="form-group">
                <label for="sort">顺序</label>
                <input
                  v-model="course.sort"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  id="sort"
                  placeholder="顺序"
                />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              取消
            </button>
            <button @click="save()" type="button" class="btn btn-primary">
              保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- content Modal -->
    <div
      class="modal fade"
      id="content-model"
      tabindex="-1"
      role="dialog"
      aria-labelledby="myModalLabel"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">内容编辑</h4>
          </div>
          <div class="modal-body">
            <File
              v-bind:input-id="'file-upload'" 
              v-bind:text="'上传文件'"
              v-bind:suffixs="['png','jpg','jpeg', 'mp4', 'avi', 'wmv', 'flv']"
              v-bind:afterUpload="afterUploadContentFile"
              v-bind:use="FILE_USE.COURSE.key"
            ></File>
            <table id="file-table" class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th>名称</th>
                  <th>地址</th>
                  <th>大小</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="file in files" :key="file.id">
                  <td>{{file.name}}</td>
                  <td>{{file.url}}</td>
                  <td>{{file.size | formatFileSize}}</td>
                  <td>
                    <button v-on:click="delFile(file)" class="btn btn-white btn-xs btn-warning btn-round">
                        删除
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
            <form class="form-horizontal">
              <div class="form-group">
                <div class="col-lg-12">
                  <div id="content"></div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              取消
            </button>
            <button @click="saveContent()" type="button" class="btn btn-primary">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- /.span -->
</template>
<script>
import Pagination from "../../components/pagination";
import File from "../../components/file";
import Toast from "../../../public/static/js/toast";
import Loading from "../../../public/static/js/loading";
import Confirm from "../../../public/static/js/confirm";
import Validator from "../../../public/static/js/validator";
import Tool from "../../../public/static/js/tool";

export default {
  components: { Pagination, File },
  name: "courses",
  data() {
    return {
      base: `${process.env.VUE_APP_BASE_URL}/business`,
      course: {},
      courses: [],
      categories: {},
      tree: {},
      teachers: [],
      files: [],
      CHARGE: COURSE_CHARGE,
      LEVEL: COURSE_LEVEL,
      STATUS: COURSE_STATUS,
      FILE_USE: FILE_USE
    };
  },

  mounted: function () {
    // 调用父组件的activeSidebar方法
    // this.$parent.activeSidebar("business-course-sidebar")
    let _this = this;
    // 初始化每页条数
    _this.$refs.Pagination.size = 10;
    _this.allCategories();
    _this.allTeachers()
    _this.list(1);
  },
  methods: {
    addModel() {
      let _this = this;
      _this.course = {};
      _this.tree.checkAllNodes(false);
      $("#course-form").modal("show");
    },

    contentModel(course) {
      let _this = this
      _this.course = $.extend({}, course);
      let id = course.id
      $('#content').summernote({
        focus: true,
        height: 400,
        lang: 'zh-CN'
      })
      // 清空
      $('#content').summernote('code', '')
      _this.listContentFile()
      Loading.show()
      // 读取数据库内容
      _this.$axios.get(`${_this.base}/admin/courses/contents/${id}`).then((res) => {
        Loading.hide()
        if (res.data.success) {
          $("#content-model").modal({backdrop: 'static', keyboard: false});
          if (res.data.data != null) {
            $('#content').summernote('code', res.data.data.content)
          }
        }else {
          Toast.warning('内容获取失败')
        }
      }).catch(() => {
        Loading.hide()
        Toast.error('系统异常')
      })
    },
    saveContent() {
      let _this = this
      
      let content = $('#content').summernote('code')
      Loading.show()
      _this.$axios.post(`${_this.base}/admin/courses/contents`, {
        id: _this.course.id,
        content: content
      }).then((res) => {
        Loading.hide()
        if(res.data.success) {
          Toast.success('内容保存成功')
        } else{
          Toast.warning('内容保存失败')
        }
      }).catch(() => {
        Loading.hide()
        Toast.error('系统异常')
      })
    },

    list(page) {
      let _this = this;
      Loading.show();
      _this.$axios
        .get(`${_this.base}/admin/courses`, {
          params: {
            page: page,
            size: _this.$refs.Pagination.size,
          },
        })
        .then((res) => {
          Loading.hide();
          _this.courses = res.data.data.list;
          _this.$refs.Pagination.render(page, res.data.data.total);
        })
        .catch(() => {
          Loading.hide();
          Toast.error("系统异常");
        });
    },
    save() {
      let _this = this;
      /* if (!Validator.require(_this.course.name, '名称')
                || !Validator.require(_this.course.courseId, '课程ID')
                || !validator.length(_this.course.courseId, '课程ID' , 1, 8)) {
                return
            } */

      let categories = _this.tree.getCheckedNodes();
      if (Tool.isEmpty(categories)) {
        Toast.warning("请选择分类");
        return;
      }
      _this.course.categories = categories;
      Loading.show();
      _this.$axios
        .post(`${_this.base}/admin/courses`, _this.course)
        .then((res) => {
          Loading.hide();
          if (res.data.success) {
            $("#course-form").modal("hide");
            Toast.success("添加成功");
            _this.list(_this.$refs.Pagination.page);
          } else {
            Toast.error("添加失败");
          }
        })
        .catch(() => {
          Loading.hide();
          Toast.error("系统异常");
        });
    },
    editModel(course) {
      let _this = this;
      // 使用空对象复制，防止编辑时直接修改data的属性(vue双向绑定会即时渲染)
      _this.course = $.extend({}, course);
      _this.listCategories(course.id);
      $("#course-form").modal("show");
    },
    del(courseId) {
      Confirm.show("确定要删除吗?", () => {
        let _this = this;
        Loading.show();
        _this.$axios
          .delete(`${_this.base}/admin/courses/${courseId}`)
          .then((res) => {
            Loading.hide();
            if (res.data.success) {
              Toast.success("删除成功");
              _this.list(_this.$refs.Pagination.page);
            } else {
              Toast.error("删除失败");
            }
          })
          .catch(() => {
            Loading.hide();
            Toast.error("系统异常");
          });
      });
    },
    toChapter(course) {
      let _this = this;
      SessionStorage.set(SESSION_KEY_COURSE, course);
      _this.$router.push("/business/chapter");
    },
    allCategories() {
      let _this = this;
      Loading.show();
      _this.$axios
        .get(`${_this.base}/admin/categories`)
        .then((res) => {
          Loading.hide();
          _this.categories = res.data.data;
          // 注意ajax的异步加载，一定要在then后再操作数据
          _this.initTree();
        })
        .catch(() => {
          Loading.hide();
          Toast.error("系统异常");
        });
    },
    allTeachers() {
      let _this = this;
      Loading.show();
      _this.$axios
        .get(`${_this.base}/admin/teachers/all`)
        .then((res) => {
          Loading.hide();
          _this.teachers = res.data.data;
        })
        .catch(() => {
          Loading.hide();
          Toast.error("系统异常");
        });
    },
    listCategories(courseId) {
      let _this = this;
      _this.$axios
        .get(`${_this.base}/admin/courses/categories/${courseId}`)
        .then((res) => {
          Loading.hide();
          _this.categories = res.data.data;
          _this.tree.checkAllNodes(false);
          // 勾选查询到的分类
          for (let i = 0; i < this.categories.length; i++) {
            let node = _this.tree.getNodeByParam(
              "id",
              this.categories[i].categoryId
            );
            _this.tree.checkNode(node);
            _this.tree.expandNode(node, true, false, true);
          }
        })
        .catch(() => {
          Loading.hide();
        });
    },

    initTree() {
      let _this = this;
      let settings = {
        check: {
          enable: true,
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parent",
            rootPId: "00000000",
          },
        },
      };

      let zNodes = _this.categories;
      _this.tree = $.fn.zTree.init($("#tree"), settings, zNodes);
      // 展开所有节点
      _this.tree.expandAll(false);
    },
    afterUpload(res) {
        let _this = this;
        let image = res.data.data;
        _this.$set(_this.course, "image", image.path)
    },
    listContentFile() {
    let _this = this
    _this.$axios.get(`${_this.base}/admin/courses/contents/files/${_this.course.id}`).then((res) => {
      if (res.data.success) {
        _this.files = res.data.data
      } else {
        Toast.error('获取文件列表失败')
      }
      }).catch(() => {
        Toast.error('获取文件列表失败')
      })
    },
    afterUploadContentFile(res) {
      let _this = this
      let file = res.data.data
      let contentFile = {}
      // 保存到course-content-file
      contentFile.courseId = _this.course.id
      contentFile.url = file.path
      contentFile.name = file.name
      contentFile.size = file.size

      _this.$axios.post(`${_this.base}/admin/courses/contents/files`, contentFile).then((res) => {
        if(res.data.success) {
          Toast.success('文件上传成功')
          _this.files.push(res.data.data)
        } else {
          Toast.error('文件上传失败')
        }
      }).catch(() => {
        Toast.error('文件上传失败')
      })
    },
    delFile(file) {
      let _this = this
      Confirm.show('确认删除课程内容文件吗?', function() {
        _this.$axios.delete(`${_this.base}/admin/courses/contents/files/${file.id}`).then((res) => {
            if(res.data.success) {
              Toast.success('文件删除成功')
              Tool.removeObj(_this.files, file)
            }
          }).catch(() => {
            Toast.error('文件删除失败')
          })
        })
    }
  },
  
};
</script>
<style  scoped>
  .caption h3 {
    font-size: 20px;
  }

    @media (max-width: 1199px) {
    .caption h3 {
      font-size: 16px;
    }
  }
</style>